package com.dengc.controller;

import com.dengc.pojo.SysRole;
import com.dengc.pojo.SysUser;
import com.dengc.service.SysRoleService;
import com.dengc.service.SysUserService;
import com.dengc.utils.Contants;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    //进入用户信息页面
    @RequestMapping("/togetuser")
    public  String togetuser(){
        return "sysUser/list";
    }

    //用户信息界面查看功能
    @RequestMapping("/lookoverUser/{id}")
    public String lookoverUser(@PathVariable("id") Integer id,
                               HttpServletRequest request){
        SysUser sysUser = sysUserService.getIdSysUser(id);
        request.setAttribute("sysUser",sysUser);
        return "sysUser/view";
    }
    //用户信息界面修改功能 1.进入页面并且显示信息
    @RequestMapping("/SysUserUpdate/{id}")
    public String UserUpdate1(@PathVariable("id") Integer id,
                             HttpServletRequest request){
        //角色
        List<SysRole> allRoles = sysRoleService.getAllRoles();
        //角色下拉框显示的数据
        request.setAttribute("roleList",allRoles);

        SysUser sysUser = sysUserService.getIdSysUser(id);
        request.setAttribute("sysUser",sysUser);
        return "sysUser/update";
    }
    //用户信息界面修改功能 2.修改信息
    @RequestMapping("/sys/user/update")
    @ResponseBody
    public String UserUpdate2(SysUser sysUser,HttpServletRequest request){
        int num =  sysUserService.updateSysUser(sysUser);
        if(num>0){
            //保存成功
            return "<script>alert('修改成功');location.href='"+request.getContextPath()+"/sys/user/list'</script>";
        }else{
            //保存失败
            return "<script>alert('修改失败');location.href='"+request.getContextPath()+"/sys/user/list'</script>";
        }
    }

    //用户信息界面添加用户信息功能 1.进入添加页面
    @RequestMapping("/SysUserToAdd")
    public String SysUserToAdd1(HttpServletRequest request){
        //角色
        List<SysRole> allRoles = sysRoleService.getAllRoles();
        //角色下拉框显示的数据
        request.setAttribute("roleList",allRoles);
        return "sysUser/add";
    }
    //用户信息界面添加用户信息功能 2.添加信息
    @RequestMapping("/sys/user/add")
    @ResponseBody
    public String SysUserToAdd2(@RequestParam(value = "rpassword",required = false) String rpassword ,
                                @RequestParam(value = "password",required = false) String password ,
                                SysUser sysUser, HttpServletRequest request, HttpSession session,
                                @RequestParam(value = "photo_image",required = false) MultipartFile photoImage)
    {
        ServletContext context = session.getServletContext();
        String path = context.getRealPath("/statics/uploadFile/");
        File file = new  File(path);
        if (!file.exists()){
            //如果没有自动创建文件夹
            file.mkdirs();
        }
        if(photoImage!=null){
            //上传用户照片信息
            String fileName = photoImage.getOriginalFilename();//文件名
            String fileNameSuffix = FilenameUtils.getExtension(fileName);
            //判断文件大小
            if (photoImage.getSize()>1024*1024*5){
               return  "<script>alert('上传文件过大！');location.href='"+request.getContextPath()+"/SysUserToAdd'</script>";
            }
            if (!fileNameSuffix.equalsIgnoreCase("jpg")&&
                !fileNameSuffix.equalsIgnoreCase("png")&&
                !fileNameSuffix.equalsIgnoreCase("pneg")&&
                !fileNameSuffix.equalsIgnoreCase("bmp")){
                return  "<script>alert('上传文件类型不正确！');location.href='"+request.getContextPath()+"/SysUserToAdd'</script>";
            }
            //新文件名(生产唯一的文件名)
            String destFileName ="images-"+UUID.randomUUID().toString()+"."+fileNameSuffix;
            File desFile = new File(path,destFileName);
            try {
                photoImage.transferTo(desFile);
                sysUser.setPhoto(destFileName);
            } catch (IOException e) {
                request.setAttribute("msg","上传失败");
                throw new RuntimeException(e);
            }
        }
        if ("".equals(rpassword) || "".equals(password)){
            return "<script>alert('密码不能为空！');location.href='"+request.getContextPath()+"/SysUserToAdd'</script>";
        }else if (!password.equals(rpassword)){
            return "<script>alert('两次输入密码不一致！');location.href='"+request.getContextPath()+"/SysUserToAdd'</script>";
        }else {
            //添加用户
            SysUser user = (SysUser) session.getAttribute(Contants.USERSESSION);
            sysUser.setCreateTime(new Date());
            sysUser.setCreatedUserId(user.getId());
            int num =  sysUserService.addUser(sysUser);
            if(num>0){
                //保存成功
                return "<script>alert('新增成功');location.href='"+request.getContextPath()+"/sys/user/list'</script>";
            }else{
                //保存失败
                return "<script>alert('新增失败');location.href='"+request.getContextPath()+"/sys/user/list'</script>";
            }
        }
    }


    //进入修改密码页面
    @RequestMapping("/toupdatePassword")
    public String toupdatePassword(){
        return "sysUser/updatePassword";
    }

    //修改密码业务
    @RequestMapping("/sysUser/savePassword")
    public String savePassword(@RequestParam("oldPassword") String oldPassword,
                               @RequestParam("newPassword") String newPassword,
                               @RequestParam("reNewPassword") String reNewPassword,
                               HttpServletRequest request,
                               HttpSession session
    ){
        SysUser sysUser = (SysUser) session.getAttribute(Contants.USERSESSION);
        if (!newPassword.equals(reNewPassword)){
            request.setAttribute("message","两次输入的密码不同！");
            return "sysUser/updatePassword";
        }else if (!oldPassword.equals(sysUser.getPassword())){
            request.setAttribute("message","旧密码不正确！");
            return "sysUser/updatePassword";
        }else {
            //修改密码
            //修改完的新密码保存进当前Sys_User对象中
            sysUser.setPassword(newPassword);
            //调用修改方法对数据库中数据进行更新
            sysUserService.updateSysUser(sysUser);
            //移出session验证
            session.removeAttribute(Contants.USERSESSION);
            return "login";
        }
    }

    //用户信息界面删除用户信息功能
    @RequestMapping("/SysUserDelete/{id}")
    @ResponseBody
    public String deletUser(@PathVariable("id") Integer id,HttpServletRequest request){
       int num = sysUserService.deleteUser(id);
        if(num>0){
            //删除成功
            return "<script>alert('删除成功');location.href='"+request.getContextPath()+"/sys/user/list'</script>";
        }else{
            //删除失败
            return "<script>alert('删除失败');location.href='"+request.getContextPath()+"/sys/user/list'</script>";
        }
    }

    //动态查询分页展示
    @RequestMapping("/sys/user/list")
    public String getAllSysUserList(
            @RequestParam(value = "queryRealName",required = false) String realName,
            @RequestParam(value = "queryRoleId",required = false) Integer roleId,
            @RequestParam(value = "pageIndex",required = false) Integer pageIndex,
            HttpServletRequest request){
        //角色
        List<SysRole> allRoles = sysRoleService.getAllRoles();
        //角色下拉框显示的数据
        request.setAttribute("roleList",allRoles);

        //用户
        SysUser sysUserCondition = new SysUser();
        if(realName!=null && !"".equals(realName)){
            sysUserCondition.setRealName(realName);
            //回显模糊查询数据
            request.setAttribute("queryRealName",realName);
        }
        if (roleId!=null && !"".equals(roleId)){
            sysUserCondition.setRoleId(roleId);
            //回显roleid
            request.setAttribute("queryRoleId",roleId);
        }
        int pageNum = 1;//默认设置为第一页
        if (pageIndex!=null){
            pageNum = pageIndex;
        }
        PageInfo<SysUser> pageInfo = sysUserService.getSysUserByPage(sysUserCondition, pageNum);
        request.setAttribute("pageInfo",pageInfo);
        return "sysUser/list";
    }


}
